package com.javen.controller;

import com.javen.entites.CommonResult;
import com.javen.entites.Order;
import com.javen.service.OrderFeignInterface;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author Javen
 */
@RestController
@Slf4j
@DefaultProperties(defaultFallback = "globalFallback")
public class OrderController {

    @Resource
    private OrderFeignInterface orderService;

    @PostMapping(value = "/feign/consumer/order/create")
    public CommonResult create(Order order) {
        return orderService.create(order);
    }

    @GetMapping(value = "/feign/consumer/order/get/{id}")
    public CommonResult get(@PathVariable("id") Long id) {
        return orderService.get(id);
    }

    @HystrixCommand(fallbackMethod = "timeOutHandler", commandProperties = {
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "200")
    })
    @GetMapping("/feign/consumer/order/hystrix/timeout/{id}")
    public CommonResult timeOut(@PathVariable("id") Long id) {
        return orderService.timeOut(id);
    }

    @GetMapping("/feign/consumer/order/error")
    @HystrixCommand
    public String testError() {
        int age = 10 / 0;
        return "测试异常....";
    }

    public CommonResult timeOutHandler(Long id) {
        log.info("客户端 timeOutHandler  线程名称: " + Thread.currentThread().getName() + " 系统繁忙请稍后再试 id:" + id);
        return new CommonResult(500, "客户端 timeOutHandler 线程名称: " + Thread.currentThread().getName() + " 系统繁忙请稍后再试", id);
    }

    public String globalFallback() {
        return "全局异常处理信息，请稍后再试...";
    }
}
